package com.toolkit.interceptor;

import com.alibaba.fastjson2.JSON;
import com.toolkit.common.Constants;
import com.toolkit.enumData.ExceptionCodeMsg;
import com.toolkit.exceptionHandler.BusinessException;
import com.toolkit.module.userInfo.dto.UserLoginDto;
import com.toolkit.util.BaseContextHandler;
import com.toolkit.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor  implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    //controller层之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri= request.getRequestURI();
       if(uri.equals("/userInfo/getAppToken")){       //放行滴滴推送接口
           return true;
       }
        //从请求头中获取所需参数
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            throw new BusinessException(ExceptionCodeMsg.TOKEN_VALID_CODE);
        }
        //从redis中获取token并校验
        String userLoginStr=redisUtil.getCacheObject(token);
        if(StringUtils.isEmpty(userLoginStr)){
            throw new BusinessException(ExceptionCodeMsg.TOKEN_VALID_CODE);
        }
        redisUtil.setCacheObject(token, userLoginStr, 30, TimeUnit.DAYS);
        UserLoginDto userLoginDto = JSON.parseObject(userLoginStr, UserLoginDto.class);
        BaseContextHandler.set(Constants.USER_INFO_KEY, userLoginDto);
       return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
    }

}